package com.yifei.controller.auth;

import com.yifei.annotation.Log;
import com.yifei.model.dto.auth.CaptchaResult;
import com.yifei.model.dto.auth.LoginResult;
import com.yifei.model.enums.BusinessTypeEnum;
import com.yifei.model.enums.ResultCode;
import com.yifei.model.form.auth.LoginFrom;
import com.yifei.model.result.Result;
import com.yifei.service.auth.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: 权限管理
 * @Author: yiFei
 * @date: 2023/9/21 21:31
 */
@Api(tags = "权限管理")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    @Log(title = "权限管理", businessType = BusinessTypeEnum.LOGIN, excludeParamNames = {"password"})
    public Result<LoginResult> login(@RequestBody LoginFrom loginFrom) {
        ResultCode resultCode = authService.checkCaptcha(loginFrom.getVerifyCode(), loginFrom.getVerifyCodeKey());
        // 未返回错误表示验证码正确
        if (ObjectUtils.isEmpty(resultCode)) {
            LoginResult loginResult = authService.login(loginFrom.getUsername(), loginFrom.getPassword());
            return Result.success(loginResult);
        } else {
            // 返回验证码错误
            return Result.customize(resultCode, null);
        }

    }

    @ApiOperation(value = "注销")
    @ApiImplicitParam(name = "Authorization", value = "Token", required = true, dataType = "String", paramType = "header")
    @DeleteMapping("/logout")
    public Result<Object> logout() {
        authService.logout();
        return Result.success();
    }

    @ApiOperation(value = "刷新用户token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "Token", required = true, dataType = "String", paramType = "header"),
            @ApiImplicitParam(name = "token", value = "已经过期的Token", dataType = "String", required = true),
            @ApiImplicitParam(name = "refreshToken", value = "未过期用于刷新的Token", dataType = "String", required = true)
    })
    @PostMapping("/refresh")
    public Result<LoginResult> refreshToken(@RequestParam String token, @RequestParam String refreshToken) {
        LoginResult refreshTokenResult = authService.refreshToken(token, refreshToken);
        return Result.success(refreshTokenResult);
    }

    @ApiOperation(value = "获取验证码")
    @GetMapping("/captcha")
    public Result<CaptchaResult> getCaptcha() {
        CaptchaResult captcha = authService.getCaptcha();
        return Result.success(captcha);
    }
}
